cc1b91fe3951ee9cbb5aee21c28e868dd6eae242
[nextcloud-desktop.git] /
1 //
2 //  ShareeSuggestionsDataSource.swift
3 //  FileProviderUIExt
4 //
5 //  Created by Claudio Cambra on 2/4/24.
6 //
7
8 import Foundation
9 import NextcloudKit
10 import OSLog
11 import SuggestionsTextFieldKit
12
13 class ShareeSuggestionsDataSource: SuggestionsDataSource {
14     let kit: NextcloudKit
15     var suggestions: [Suggestion] = []
16     var inputString: String = "" {
17         didSet { Task { await updateSuggestions() } }
18     }
19
20     init(kit: NextcloudKit) {
21         self.kit = kit
22     }
23
24     private func updateSuggestions() async {
25         let sharees = await fetchSharees(search: inputString)
26         Logger.shareeDataSource.info("Fetched \(sharees.count, privacy: .public) sharees.")
27         suggestions = suggestionsFromSharees(sharees)
28         NotificationCenter.default.post(name: SuggestionsChangedNotificationName, object: self)
29     }
30
31     private func fetchSharees(search: String) async -> [NKSharee] {
32         Logger.shareeDataSource.debug("Searching sharees with: \(search, privacy: .public)")
33         return await withCheckedContinuation { continuation in
34             kit.searchSharees(
35                 search: inputString,
36                 page: 1,
37                 perPage: 20,
38                 completion: { account, sharees, data, error in
39                     defer { continuation.resume(returning: sharees ?? []) }
40                     guard error == .success else {
41                         Logger.shareeDataSource.error(
42                             "Error fetching sharees: \(error.description, privacy: .public)"
43                         )
44                         return
45                     }
46                 }
47             )
48         }
49     }
50
51     private func suggestionsFromSharees(_ sharees: [NKSharee]) -> [Suggestion] {
52         return sharees.map {
53             Suggestion(
54                 imageName: "person.fill",
55                 displayText: $0.label.isEmpty ? $0.name : $0.label,
56                 data: $0
57             )
58         }
59     }
60 }